package com.lagou.utils;

import com.lagou.annotation.Service;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author: lcz
 * @date: Created in 14:38 2020/10/5
 * @description:
 */
@Service
public class ConnectionUtils {
    //存储当前线程的连接
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * @author: lcz
     * @date: Created in 14:45 2020/10/5
     * @description: 从当前线程获取连接
     */
    public Connection getCurrentThreadConn () throws SQLException {
        Connection connection = threadLocal.get();
        if (null == connection) {
            //从连接池中获取连接并绑定到当前线程中
            connection = DruidUtils.getInstance().getConnection();
            //绑定到当前线程
            threadLocal.set(connection);
        }
        return connection;
    }
}
